package buildfactroy

import (
	"fmt"
	"gitee.com/cristiane/micro-mall-api/pkg/util/email"
	"gitee.com/ichub/goconfig/common/base/baseutils/fileutils"
	utils "gitee.com/ichub/goconfig/common/base/baseutils/stringutils"

	"gitee.com/ichub/gofactroy/factroy/buildfactroy/code"
	"gitee.com/ichub/gofactroy/factroy/buildfactroy/join"
	"gitee.com/ichub/gofactroy/factroy/buildfactroy/rpc"
	"gitee.com/ichub/gofactroy/factroy/buildfactroy/test"
	"gitee.com/ichub/gofactroy/factroy/dbfactroy"
	"github.com/sirupsen/logrus"
	"log"
	"os"
	"os/exec"
	"strings"
)

type BuildGoFactroy struct {
	DbFactroy *dbfactroy.DbFactroy

	modelfactroy      code.ModelFactroy
	dtoFactroy        code.DtoFactroy
	daofactroy        code.DaoFactroy
	servicefactroy    code.ServiceFactroy
	rpcfactroy        rpc.RpcFactroy
	controllerfactroy code.WebFactroy

	testfactroy test.TestFactroy
}

func (tool *BuildGoFactroy) IniLog() *BuildGoFactroy {
	logFile, err := os.OpenFile("./test.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open log service failed, err:", err)
		return tool
	}
	log.SetOutput(logFile)
	return tool
}
func (this *BuildGoFactroy) BuildProto2Go() {
	//_ = this.RmGenProto()

	var basepath = fileutils.FindRootDir()
	os.Chdir(basepath + "/data/bin")
	var cmdPath = basepath + "/data/bin/pb.bat"
	logrus.Info(cmdPath)
	var b = fileutils.CheckFileExist(cmdPath)
	if !b {
		logrus.Error("文件路径不对" + cmdPath)
		return
	}
	cmd := exec.Command(cmdPath)
	out, _ := cmd.Output()
	logrus.Info(string(out))
}

/*
单表生成
ret key=filename value=content
*/
func (buildtool *BuildGoFactroy) BuildTable() (dir, f, c string) {

	tool := buildtool.DbFactroy
	tool.GenDir = dbfactroy.Gendir
	tool.GenDirTest = dbfactroy.GendirTest
	tool.FindTableComment()

	tool.Tables = append(tool.Tables, tool.Table)

	fmt.Printf("gen %d model %s:\n", tool.I, tool.Table)
	dir, f, c = buildtool.modelfactroy.Build(tool)

	fmt.Printf("gen dto %s:\n", tool.Table)
	buildtool.dtoFactroy.Build(tool)

	fmt.Printf("gen dao %s:\n", tool.Table)
	buildtool.daofactroy.Build(tool)

	fmt.Printf("gen service %s:\n", tool.Table)
	buildtool.servicefactroy.Build(tool)

	fmt.Printf("gen rpc %s:\n", tool.Table)
	dir, f, c = buildtool.rpcfactroy.Build(tool)

	fmt.Printf("gen web %s:\n", tool.Table)
	buildtool.controllerfactroy.Build(tool)

	fmt.Printf("gen rpcController %s:\n", tool.Table)
	buildtool.controllerfactroy.BuildRpc(tool)

	fmt.Printf("gen test %d %s:\n\n", tool.I, tool.Table)
	buildtool.testfactroy.Build(tool)

	tool.I++
	return
}

func (buildtool *BuildGoFactroy) SendEmail(subj, msg string) {
	emailReq := &email.SendRequest{
		Receivers: []string{"leijmdas_s180@163.com"},
		Subject:   subj,
		Message:   msg,
	}
	email.DefaultEmailHelper = &email.Client{}
	// retry send email
	err := email.DefaultEmailHelper.SendEmail(emailReq)
	if err != nil {
		fmt.Println(err.Error())
		panic(err.Error())
	}
}

func (buildtool *BuildGoFactroy) BuildTables() (dir, f, c string) {
	var cs []string
	tool := buildtool.DbFactroy

	var tables []dbfactroy.Tables = tool.FindTables()

	for _, v := range tables {
		tool.Table = v.TableName
		tool.TableComment = &v.TableComment
		dir, f, c = buildtool.BuildTable()
		cs = append(cs, c)
	}

	for _, v := range tables {
		fmt.Println(string(v.TableName) + "表转换完成！")
	}
	buildtool.BuildInfos()

	subj := "生成单表Go代码：" + utils.Ip4() + " " + tool.Table
	//msg := strings.Join(tool.TestFiles, "\n")
	cc := ""
	for _, v := range tool.Dfcs {
		cc = cc + v.Content
	}
	c = c + cc
	c = strings.ReplaceAll(c, "\n", "<br/>")
	c = strings.ReplaceAll(c, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;")
	c = strings.ReplaceAll(c, " ", "&nbsp;")

	buildtool.DbFactroy.SendEmail(subj, c)

	return
}

func (buildtool *BuildGoFactroy) BuildInfos() {
	tool := buildtool.DbFactroy
	tool.BuildInfo(dbfactroy.Gendir)
	tool.BuildInfoTest(dbfactroy.GendirTest)

}

func (buildtool *BuildGoFactroy) BuildMultiQueryEmployee() {

	multiquery := &join.JoinQuery{}
	multiquery.Ini(buildtool.DbFactroy, "employee,department,joblevel")
	multiquery.SelectFields(`employee.beginDate,employee.id,employee.name,department.name`)
	multiquery.Keys["joblevel.id"] = "employee.jobLevelId"
	multiquery.Keys["department.id"] = "employee.departmentId"

	multiquery.Build(buildtool.DbFactroy)

}

func (buildtool *BuildGoFactroy) BuildMqCmsContentColumn() {

	multiquery := &join.JoinQuery{}
	multiquery.Ini(buildtool.DbFactroy, "cms_content,cms_column")
	multiquery.SelectFields("cms_column.id,cms_content.content_id")
	multiquery.Keys["cms_column.id"] = "cms_content.content_id"
	multiquery.TableAlias = "CmsContentColumn"
	multiquery.Build(buildtool.DbFactroy)
}

func (buildtool *BuildGoFactroy) buildEmpMulti() {
	/*
	 多表关联查询
	*/
	multiQuery := &join.JoinQuery{}
	multiQuery.Ini(buildtool.DbFactroy, "employee,department,joblevel")
	multiQuery.SelectFields("employee.id,employee.name,employee.beginDate,department.name,joblevel.name")
	multiQuery.Keys["joblevel.id"] = "employee.jobLevelId"
	multiQuery.Keys["department.id"] = "employee.departmentId"
	//multiQuery.TableAlias="employee_dpt"
	multiQuery.Build(buildtool.DbFactroy)
	multiQuery.LogDfc()

}
